package com.lmind.core;

import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IoTool {
	
	public static int copyStream(OutputStream output, InputStream input) throws IOException {
		
		int totalRead = 0;
		byte[] buffer = new byte[256];
		
		while (true) {
			int r = input.read(buffer);
			if (r == -1)
				break;
			output.write(buffer, 0, r);
			totalRead += r;
		}
		
		return totalRead;
	}
	
	public static void safeClose(Closeable closeable) {
		try {
			closeable.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void safeFlush(Flushable flushable) {
		try {
			flushable.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void safeFlushAndClose(OutputStream output) {
		safeFlush(output);
		safeClose(output);
	}
}
